﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MKAdmin.ToolKit
{
    /// <summary>
    /// webconfig中 AppSettings 节点配置信息 读取器
    /// </summary>
    public static class AppSettingsKit
    {
        /// <summary>
        /// 读取值
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static string GetValue(string key)
        {
            ConfigurationManager.RefreshSection("appSettings");
            return ConfigurationManager.AppSettings[key] ?? string.Empty;
        }

        /// <summary>
        /// 配置信息 key 为 ip
        /// </summary>
        public const string KEY_IP = "IP";

        /// <summary>
        /// 配置信息 key 为 Port
        /// </summary>
        public const string KEY_PORT = "Port";

        /// <summary>
        /// 配置信息 key 为 AppID
        /// </summary>
        public const string KEY_AppID = "AppID";

        /// <summary>
        /// 配置信息 key 为 Secret
        /// </summary>
        public const string KEY_Secret = "Secret";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool UpdateAppSettings(string key, string value)
        {
            var _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (!_config.HasFile)
            {
                throw new ArgumentException("程序配置文件缺失！");
            }
            KeyValueConfigurationElement _key = _config.AppSettings.Settings[key];
            if (_key == null)
                _config.AppSettings.Settings.Add(key, value);
            else
                _config.AppSettings.Settings[key].Value = value;

            _config.Save(ConfigurationSaveMode.Modified);
            return true;
        }
    }
}
